package com.hmall.order.web;

import com.hmall.common.client.AdderssFeignClient;
import com.hmall.common.client.SearchFeignClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.itercepter.MyIntercepter;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.UserOrder;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.impl.OrderDetailService;
import com.hmall.order.service.impl.OrderLogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;

@RestController
@RequestMapping("order")
public class OrderController {

   @Autowired
   private IOrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;


   @Autowired
   private SearchFeignClient feignClient;

   @Autowired
   private AdderssFeignClient adderssFeignClient;




   @GetMapping("{id}")
   public Order queryOrderById(@PathVariable("id") Long orderId) {
      return orderService.getById(orderId);
   }

   @PostMapping
    public Long getOrderId(@RequestBody UserOrder userOrder){
      //通过feign  获取item
      Item item = feignClient.findItemById(userOrder.getItemId());
      //计算总价
      Integer totalFee = Math.toIntExact(userOrder.getNum() * item.getPrice()/100);
      //封装 order对象
       Timestamp id = new Timestamp(System.currentTimeMillis());

       Order order = new Order();
       order.setId(id.getTime());
      order.setTotalFee(totalFee.longValue());
      order.setPaymentType(userOrder.getPaymentType());
      order.setStatus(1);
      order.setUserId(Long.valueOf(MyIntercepter.threadLocal.get()));
      //保存到数据库
      orderService.save(order);
      //封装  OrderDetail
      OrderDetail orderDetail = new OrderDetail();
      orderDetail.setOrderId(order.getId());
      orderDetail.setItemId(item.getId());
      orderDetail.setNum(userOrder.getNum());
      orderDetail.setName(item.getName());
      orderDetail.setPrice(item.getPrice());

      orderDetailService.save(orderDetail);

       Address address = adderssFeignClient.findAddressById(userOrder.getAddressId());
       OrderLogistics orderLogistics = new OrderLogistics();
       orderLogistics.setOrderId(order.getId());
       orderLogistics.setContact(address.getContact());
       orderLogistics.setCity(address.getCity());
       orderLogistics.setTown(address.getTown());
       orderLogistics.setStreet(address.getStreet());
       orderLogistics.setMobile(address.getMobile());
       orderLogistics.setCreateTime(order.getCreateTime());
       orderLogistics.setProvince(address.getProvince());
       orderLogisticsService.save(orderLogistics);



       return order.getId();
       //


   }
}
